<template>
  <el-drawer class="dia-style" :title="title" :visible.sync="open" width="60%" :close-on-click-modal="false" size="50%" :wrapper-closable="false" @close="resetForm">
    <el-row>
      <el-col :span="24">
        <div class="tips">基础信息</div>
      </el-col>
    </el-row>

    <div class="dia-form">
      <HkForm
        ref="hkFormRef"
        label-width="140"
        :form-labels="formObj.formLabels"
        :rules="formObj.formRules"
        label-position="left"
        :data="formData"
        :dict-list="formObj.dictList"
        :btn-hidden="true"
        @handleEvent="handleEvent"
      >
        <template #filter-cacheTime="scope">
          <el-row>
            <el-col :span="18" style="margin-right: 5px">
              <el-select v-model="formData.cacheTime" style="width: 100%" placeholder="请选择" filterable>
                <el-option
                  v-for="item in formObj.dictList.cacheTimeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="4">分钟</el-col>
          </el-row>
        </template>
        <!--      外部资源      -->
        <template #filter-implement>
          <el-button type="primary" icon="el-icon-video-play" plain @click="handleSql">执行</el-button>
          <div v-if="isShow" class="slqDiv">
            <div class="floor1">
              <span>执行结果</span>
            </div>
            <div class="floor2">
              <div class="head">ID</div>
              <div class="colum">
                <div v-for="(item, index) in sqlResult" :key="index" class="colum-list">{{ item }}</div>
              </div>
            </div>
          </div>
        </template>
        <!--      内部资源      -->
        <template #filter-constantDataList="scope">
          <el-row>
            <el-col :span="20" style="margin-bottom:20px;">
              <el-button type="text" icon="el-icon-circle-plus" @click="handleAddTable">添加</el-button>
            </el-col>
            <el-col :span="4">
              <el-input
                v-model="queryParams.search"
                width="100%"
                placeholder="请输入内容"
                clearable
                @keydown.enter.native="searchTable($event)"
                @blur="searchTable($event)"
              >
                <i slot="prefix" class="el-input__icon el-icon-search" />
              </el-input>
            </el-col>
          </el-row>
          <el-row>
            <hk-table
              :loading="loading"
              :table-data="formData.constantDataList"
              :table-columns="tableFieldList"
              :total="total"
              :show-pag="true"
              :operate="true"
              :show-index="true"
              :is-need-index="true"
              :query-params="queryParams"
              @changePage="changePage"
            >
              <template #constData="scope">
                <el-input v-model="scope.row.row.constData" placeholder="请输入内容" clearable />
              </template>
              <template #operate="scope">
                <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </hk-table>
          </el-row>
        </template>
      </HkForm>
    </div>

    <!-- 底部 -->
    <div class="el-drawer-footer">
      <el-button :disabled="isDisabled" type="primary" @click="handleSubmit">保 存</el-button>
      <el-button @click="resetForm">取 消</el-button>
    </div>
  </el-drawer>
</template>

<script>
import HkForm from '@/components/Hk-Form'
import HkTable from '@/components/Hk-Table/index.vue'
import {
  getRefSqlData,
  externalRef,
  constantRef,
  externalData,
  getRefConstantList,
  delRefDataById
} from '@/api/icp/associatedData'
import { deepClone } from '@/utils/index'
import { REF_DATA_TYPE } from '@/constants/index'

export default {
  name: 'DataDialog',
  components: { HkForm, HkTable },
  props: {
    title: {
      type: String,
      default() {
        return ''
      }
    },
    form: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      open: false,
      isDisabled: true,
      queryParams: {
        id: '',
        search: '',
        current: 1,
        size: 10
      },
      formData: {
        itemType: REF_DATA_TYPE.EXTERNAL_QUERY
      },
      formObj: {
        formLabels: [
          {
            label: '数据名称',
            field: 'itemName',
            type: 'input',
            show: 'all',
            span: 24
          },
          {
            label: '数据类型',
            field: 'itemType', // 参考REF_DATA_TYPE
            type: 'select',
            list: 'typeList',
            show: 'all',
            span: 24
          },
          {
            label: 'SQL语句',
            field: 'queryExpress',
            type: 'textarea',
            attrs: { rows: 4 },
            show: REF_DATA_TYPE.EXTERNAL_QUERY,
            span: 24
          },
          {
            label: '缓存时间',
            field: 'cacheTime',
            type: 'slot',
            show: 'all',
            list: 'cacheTimeList',
            span: 24
          },
          {
            label: '',
            field: 'implement',
            type: 'slot',
            show: REF_DATA_TYPE.EXTERNAL_QUERY,
            span: 24
          },
          {
            label: '外部常量列表',
            field: 'constantDataList',
            type: 'slot',
            show: REF_DATA_TYPE.EXTERNAL_CONSTANT,
            span: 24
          }
        ],
        formRules: {
          itemName: [{ required: true, message: '数据名称不能为空', trigger: 'blur' }],
          queryExpress: [{ required: true, message: '请输入SQL语句', trigger: 'blur' }],
          itemType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }]
        },
        dictList: {
          typeList: [
            { label: '引用字典', value: REF_DATA_TYPE.EXTERNAL_QUERY },
            { label: '常量字典', value: REF_DATA_TYPE.EXTERNAL_CONSTANT }
          ],
          cacheTimeList: [
            { label: '5', value: 5 },
            { label: '10', value: 10 },
            { label: '15', value: 15 },
            { label: '30', value: 30 },
            { label: '60', value: 60 }
          ]
        }
      },
      sqlResult: [],
      isShow: false,
      tableFieldList: [{ label: '资产值', param: 'constData', type: 'slot' }],
      total: 0,
      allLabels: []
    }
  },
  watch: {
    form: {
      handler(newVal) {
        if (newVal?.id) {
          this.formData = deepClone(newVal)
          if (this.formData.itemType === REF_DATA_TYPE.EXTERNAL_CONSTANT) {
            this.total = newVal.total
            if (this.formData?.constantDataList.length > 0) {
              this.isDisabled = false
            }
          }
          this.handleEvent({ field: 'itemType', value: this.formData.itemType })
        } else {
          this.formData = {
            itemType: REF_DATA_TYPE.EXTERNAL_QUERY
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.allLabels = this.formObj.formLabels
    this.handleEvent({ field: 'itemType', value: 2 })
  },
  methods: {
    /** 显示弹窗 */
    show() {
      this.open = true
    },
    reset() {
      this.formData = {
        itemName: undefined,
        itemType: REF_DATA_TYPE.EXTERNAL_QUERY,
        queryExpress: undefined,
        cacheTime: undefined,
        constantDataList: []
      }
      this.queryParams = {
        id: undefined,
        search: undefined,
        current: 1,
        size: 10
      }
      this.handleEvent({ field: 'itemType', value: REF_DATA_TYPE.EXTERNAL_QUERY })
      this.isShow = false
      this.isDisabled = true
    },
    /** 保存 */
    handleSubmit() {
      this.$refs.hkFormRef.handleFormSubmit('formLabels').then((res) => {
        if (!this.formData?.id) {
          // 新增
          if (this.formData.itemType === REF_DATA_TYPE.EXTERNAL_QUERY) {
            externalRef(this.formData).then((res) => {
              this.$message.success('保存成功')
              this.resetForm()
              this.$emit('handleSubmit')
            })
          } else {
            let isRequire
            if (this.formData.constantDataList.length > 0) {
              isRequire = this.formData.constantDataList.every((i) => {
                return i.constData && i.constData != ''
              })
            }
            if (isRequire) {
              constantRef(this.formData).then((res) => {
                this.$message.success('保存成功')
                this.resetForm()
                this.$emit('handleSubmit')
              })
            } else {
              this.$message.error('资源值不能为空，请检查')
              return false
            }
          }
        } else {
          // 修改
          if (this.formData.itemType === REF_DATA_TYPE.EXTERNAL_CONSTANT) {
            let isRequire
            if (this.formData.constantDataList.length > 0) {
              isRequire = this.formData.constantDataList.every((i) => {
                return i.constData && i.constData != ''
              })
            }
            if (!isRequire) {
              this.$message.error('资源值不能为空，请检查')
              return false
            }
          }
          externalData(res).then((res) => {
            this.$message.success('保存成功')
            this.resetForm()
            this.$emit('handleSubmit')
          })
        }
      })
    },
    /**  取消 */
    resetForm() {
      this.reset()
      this.$refs.hkFormRef.resetForm('formLabels')
      this.open = false
    },
    /**  点击执行按钮*/
    handleSql() {
      this.$refs.hkFormRef.handleFormSubmit('formLabels').then((res) => {
        getRefSqlData(res).then((res) => {
          this.sqlResult = res
          this.isShow = true
          this.isDisabled = false
        })
      })
    },
    /** 表单触发事件*/
    handleEvent(obj) {
      if (obj.field === 'itemType') {
        if (obj.value === REF_DATA_TYPE.EXTERNAL_QUERY) {
          this.isDisabled = true
          this.formObj.formLabels = this.allLabels.filter((i) => {
            return i.show !== REF_DATA_TYPE.EXTERNAL_CONSTANT
          })
        } else {
          this.formData.constantDataList = this.formData?.constantDataList ? this.formData.constantDataList : []
          if (this.formData?.constantDataList.length === 0) {
            this.isDisabled = true
          }
          this.formObj.formLabels = this.allLabels.filter((i) => {
            return i.show !== REF_DATA_TYPE.EXTERNAL_QUERY
          })
        }
      }
    },

    /** 点击回车搜索 */
    searchTable(e) {
      this.queryParams.search = e.target.value
      if (this.formData.id) {
        this.queryParams.id = this.formData.id
        getRefConstantList(this.queryParams).then((res) => {
          this.formData.constantDataList = deepClone(res.list)
          this.total = res.total
        })
      }
    },
    /** 分页 */
    changePage(data) {
      if (this.formData.id) {
        this.queryParams.id = this.formData.id
        getRefConstantList(this.queryParams).then((res) => {
          this.formData.constantDataList = res.list
        })
      }
    },
    /**  删除按钮 */
    handleDelete(row) {
      const _self = this
      if (row.row.id && row.row.id != '') {
        this.$modal
          .confirm('是否确认删除"' + row.row.constData + '"的数据项？')
          .then(function() {
            return delRefDataById({ id: _self.formData.id, constantDataList: [row.row] })
          })
          .then((res) => {
            this.$message.success('删除成功')
            this.formData?.constantDataList.splice(row.index, 1)
          })
      } else {
        this.$modal.confirm('是否确认删除"' + row.row.constData + '"的数据项？').then(function() {
          _self.formData?.constantDataList.splice(row.index, 1)
        })
      }
      if (this.formData?.constantDataList.length == 0) {
        this.isDisabled = true
      }
    },
    /** 添加 */
    handleAddTable() {
      this.formData?.constantDataList.push({ constData: '' })
      if (this.formData?.constantDataList.length > 0) {
        this.isDisabled = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .targetTable {
  overflow: visible;
}
.dia-form{
  width:100%;
  // height:calc(188% - 36px);
}
.slqDiv {
  margin: 10px 0;
  background: #f7f7f7;
  padding: 16px;
  border-radius: 4px;

  .floor1 {
    display: flex;
    line-height: 20px;
    align-items: center;

    &::before {
      content: '';
      display: inline-block;
      background: #1890ff;
      width: 4px;
      height: 20px;
      margin-right: 10px;
    }
  }

  .floor2 {
    width: 100%;
    border: 1px solid #e8e8e8;
    height: 165px;

    .head {
      width: 100%;
      height: 41px;
      line-height: 41px;
      background: #eff4f8;
      padding-left: 16px;
      text-align: left;
      font-size: 14px;
      color: #303032;
    }

    .colum {
      height: calc(100% - 41px);
      background: #fff;
      padding: 16px;

      .colum-list {
        line-height: 30px;
      }
    }
  }
}
</style>
